/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ig.da.abs;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

/**
 *
 * @author jsanchez
 */
public abstract class AbsDA {

    private String tabla = null;
    private Connection metricada = null;
    private String pathFile = null;
    private String separator = null;
    private String[] /*StringTokenizer*/ token = null;
    private BufferedReader file = null;
    private String LINEA = null;
    private boolean readHeader=true;
    public AbsDA() throws NamingException, SQLException, ClassNotFoundException {
        Context ctx = new InitialContext();
        //
        metricada = ((DataSource) ctx.lookup("java:/METRICADA")).getConnection();
//        ResultSet re = metricada.createStatement().executeQuery("SELECT ID, NOMBRE, DRIVER, URL, USUARIO, PASSWORD FROM CONEXIONES WHERE NOMBRE='METRICADA'");
//        if (re.next()) {
//            Class.forName(re.getString("DRIVER"));
//            Properties prop = new Properties();
//            prop.put("user", re.getString("USUARIO").trim());
//            prop.put("password", re.getString("PASSWORD").trim());
//            metricada.close();
//            metricada = DriverManager.getConnection(re.getString("URL").trim(), prop);
//        }
    }

    public boolean isReadHeader() {
        return readHeader;
    }

    public void setReadHeader(boolean readHeader) {
        this.readHeader = readHeader;
    }
    
    public Connection getMetricada() {
        return metricada;
    }

    public String getPathFile() {
        return pathFile;
    }

    public String getSeparator() {
        return separator;
    }

    public String getTabla() {
        return tabla;
    }

    public void setMetricada(Connection metricada) {
        this.metricada = metricada;
    }

    public void setPathFile(String pathFile) {
        this.pathFile = pathFile;
    }

    public void setSeparator(String separator) {
        this.separator = separator;
    }

    public void setTabla(String tabla) {
        this.tabla = tabla;
    }

    public String[] getToken() {
        return token;
    }
    
    /**
     * lee y retorna la primera linea del plano
     * @return String 
     */
    public String readLine() throws FileNotFoundException, IOException {
        if (file == null) {
            file = new BufferedReader(new FileReader(new java.io.File(this.getPathFile())));
            if(!this.isReadHeader())
                this.LINEA = file.readLine();//lee la primera linea o sea para no insertar el header en la tabla
        }
        this.LINEA = file.readLine();
        if (this.LINEA != null) {
            index=0;
            token = this.LINEA.split(this.separator); //new StringTokenizer(this.LINEA, this.separator);
        } else {
            token = null;
        }
        return this.LINEA;
    }
    private int index=0;
    /**
     * lee y retorna el primer campo de la linea leida, leer primero la linea
     * con el metodo readLine
     * @return
     */
    public String nextToken() {
        String token_ = null;
        if(index < token.length)
            return token[index++];
        return null;
//        if (token.hasMoreTokens()) {
//            token_ = token.nextToken();
//        }
//        return token_;
    }

    
    public Statement getStatementInsert() throws SQLException {
        Statement preparedStatementFinal = this.metricada.createStatement();
        return preparedStatementFinal;
    }
    private String SqlString=null;
    public String getQueryNull(){
        return SqlString.replace("?", "NULL");
    }
    
    
    public PreparedStatement getPreparedStatementInsert() throws SQLException {
        PreparedStatement TEST = this.metricada.prepareStatement("SELECT * FROM " + tabla + " WHERE 1=2");
        ResultSet rs2 = TEST.executeQuery();

        numCols = rs2.getMetaData().getColumnCount();
        SqlString = "INSERT INTO " + this.tabla + "(";
        String ValueString = "VALUES (";
        for (int i = 1; i <= numCols; i++) {
            String Nom = rs2.getMetaData().getColumnName(i);
            SqlString += Nom + ",";
            ValueString += "?,";
        }
        SqlString = SqlString.substring(0, SqlString.length() - 1) + ") ";
        ValueString = ValueString.substring(0, ValueString.length() - 1) + ")";
        SqlString += ValueString;
        TEST.close();

        PreparedStatement preparedStatementFinal = this.metricada.prepareStatement(SqlString);
        for (int i = 1; i <= numCols; i++) {
            preparedStatementFinal.setNull(i, java.sql.Types.CHAR);
        }
        return preparedStatementFinal;
    }
    private int numCols = 0;

    public int getNumCols() {
        return numCols;
    }

    public void setNumCols(int numCols) {
        this.numCols = numCols;
    }

    public Statement getStatementDelete() throws Exception {
        Statement preparedStatementFinal = this.metricada.createStatement();
        return preparedStatementFinal;
    }

    public PreparedStatement getPreparedStatementUpdate() throws Exception {
        throw new Exception("No implementado..");
    }

    /**
     * metodo implementado por el usuario
     * 
     * @throws java.lang.Exception
     */
    public abstract void procesar() throws Exception;
}
